package com.sg.plmadapter.adapters;

import com.mobnut.db.model.PrimaryObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.sg.business.model.Document;
import com.sg.business.model.IPLM_Object;
import com.sg.plmadapter.windchill.PMWebservice;

public class UpdateDocumentVersion extends WindchillSyncJob {

	public UpdateDocumentVersion(PMWebservice windchill, PrimaryObject po) {
		super(windchill, po);
	}

	@Override
	protected void run(PMWebservice windchill, PrimaryObject po)
			throws Exception {
		windchill.changeRevision(po.get_id().toString());
		DBCollection collection = po.getCollection();
		collection.update(
				new BasicDBObject().append(Document.F__ID, po.get_id()),
				new BasicDBObject().append(
						"$set", //$NON-NLS-1$
						new BasicDBObject()
								.append(Document.F_LIFECYCLE,
										Document.STATUS_WORKING_ID)
								.append(Document.F_VERSIONHISTORY,
										po.getValue(Document.F_VERSIONHISTORY))
								.append(Document.F_COMMENTS, null)));
	}

	@Override
	protected String getRequestCode() {
		return IPLM_Object.REQUEST_CHANGE_REV;
	}

	@Override
	protected boolean canReload(PrimaryObject po) {
		DBCollection collection = po.getCollection();
		DBObject dbo = collection.findOne(po.queryThis());
		if (dbo.get(Document.F_MAJOR_VID).equals(
				po.getValue(Document.F_MAJOR_VID))) {
			return true;
		}
		return false;
	}

}
